import React, { useEffect, useState } from 'react';
import { 
  Card, Descriptions, Tag, Button, Space, message, 
  Divider, Steps, Table, Typography, Badge, Timeline
} from 'antd';
import { 
  CheckCircleOutlined, ClockCircleOutlined, 
  CloseCircleOutlined, UndoOutlined,
  ArrowLeftOutlined, EditOutlined,
  FileTextOutlined, DollarOutlined,
  UserOutlined, ShoppingOutlined,
  CalendarOutlined, CreditCardOutlined
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import RefundsService from '../../services/RefundsService';
import '../components.css';

const { Title, Text } = Typography;
const { Step } = Steps;

const RefundDetails = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [refund, setRefund] = useState(null);
  const [loading, setLoading] = useState(true);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [refundHistory, setRefundHistory] = useState([]);

  // 获取退款详情
  const fetchRefundDetails = async () => {
    try {
      setLoading(true);
      const response = await RefundsService.getRefundById(id);
      setRefund(response.data);
    } catch (error) {
      message.error('获取退款详情失败');
      console.error('获取退款详情错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchRefundDetails();
    // fetchRefundHistory();
  }, [id]);

  // 渲染审批状态标签
  const renderStatusTag = (status) => {
    const statusMap = {
      approved: {
        icon: <CheckCircleOutlined />,
        color: 'green',
        text: '已通过',
      },
      pending: {
        icon: <ClockCircleOutlined />,
        color: 'blue',
        text: '待审批',
      },
      denied: {
        icon: <CloseCircleOutlined />,
        color: 'red',
        text: '被否决',
      },
      rejected: {
        icon: <CloseCircleOutlined />,
        color: 'yellow',
        text: '被驳回',
      },
      revoked: {
        icon: <UndoOutlined />,
        color: 'orange',
        text: '已撤销',
      },
    };
    
    const currentStatus = statusMap[status] || { 
      icon: null, 
      color: 'default', 
      text: '未知状态' 
    };
    
    return (
      <Tag icon={currentStatus.icon} color={currentStatus.color}>
        {currentStatus.text}
      </Tag>
    );
  };

  // 退款历史记录表格列定义
  const historyColumns = [
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime',
      render: (text) => text || '-',
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      key: 'operationType',
      render: (text) => text || '-',
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      render: (text) => text || '-',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      render: (text) => text || '-',
    },
    {
      title: '状态变更',
      dataIndex: 'statusChange',
      key: 'statusChange',
      render: (_, record) => (
        <span>
          {record.oldStatus ? `${record.oldStatus} → ` : ''}
          {record.newStatus || '-'}
        </span>
      ),
    },
  ];

  if (loading) {
    return <Card loading={loading} />;
  }

  if (!refund) {
    return <Card>未找到退款信息</Card>;
  }

  return (
    <div className="refund-details">
      <Card bordered={false}>
        {/* 头部操作区 */}
        <div style={{ marginBottom: 24 }}>
          <Button type="text" icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>返回列表</Button>
          <Button type="primary" icon={<EditOutlined />} style={{ float: 'right' }} onClick={() => navigate(`/refundlist/updaterefund/${id}`)}>编辑退款</Button>
        </div>

        {/* 退款基本信息 */}
        <Title level={4} style={{ marginBottom: 24 }}><FileTextOutlined /> 基本信息</Title>
        <Descriptions bordered column={2}>
          <Descriptions.Item label="退款编号">
            <Text strong>{refund.refundNumber || '-'}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="审批状态">
            {renderStatusTag(refund.approvalStatus)}
          </Descriptions.Item>
          <Descriptions.Item label="关联客户">
            <UserOutlined /> {refund.relatedCustomer || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="关联订单">
            <ShoppingOutlined /> {refund.relatedOrder || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="退款金额">
            <DollarOutlined /> {refund.refundAmount ? `¥${parseFloat(refund.refundAmount).toFixed(2)}` : '¥0.00'}
          </Descriptions.Item>
          <Descriptions.Item label="退款方式">
            <CreditCardOutlined /> {refund.refundMethod || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="退款日期">
            <CalendarOutlined /> {refund.refundDate || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="提交时间">
            <CalendarOutlined /> {refund.submitTime || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="负责人员">
            <UserOutlined /> {refund.responsiblePerson || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="退款原因" span={2}>
            {refund.refundReason || '-'}
          </Descriptions.Item>
          <Descriptions.Item label="备注" span={2}>
            {refund.remark || '-'}
          </Descriptions.Item>
        </Descriptions>

        <Divider />

        {/* 退款进度 */}
        <Title level={4} style={{ marginBottom: 24 }}>
          <ClockCircleOutlined /> 退款进度
        </Title>
        <Steps current={getCurrentStep(refund.approvalStatus)}>
          <Step title="提交申请" description={refund.submitTime || '-'} />
          <Step 
            title="审批中" 
            description={refund.approvalStatus === 'pending' ? '进行中' : ''} 
            icon={refund.approvalStatus === 'pending' ? <ClockCircleOutlined /> : null}
          />
          <Step 
            title="处理结果" 
            description={getResultDescription(refund.approvalStatus)}
            status={getStepStatus(refund.approvalStatus)}
          />
        </Steps>

        <Divider />

        {/* 退款商品明细 */}
        {refund.products && refund.products.length > 0 && (
          <>
            <Title level={4} style={{ marginBottom: 24 }}>
              <ShoppingOutlined /> 退款商品明细
            </Title>
            <Table 
              columns={[
                { title: '商品名称', dataIndex: 'name', key: 'name' },
                { title: 'SKU', dataIndex: 'sku', key: 'sku' },
                { title: '单价', dataIndex: 'price', key: 'price', render: (text) => `¥${parseFloat(text).toFixed(2)}` },
                { title: '数量', dataIndex: 'quantity', key: 'quantity' },
                { title: '小计', dataIndex: 'subtotal', key: 'subtotal', render: (text) => `¥${parseFloat(text).toFixed(2)}` },
                { title: '退款原因', dataIndex: 'reason', key: 'reason' },
              ]}
              dataSource={refund.products}
              rowKey="id"
              pagination={false}
              bordered
            />
            <Divider />
          </>
        )}
      </Card>
    </div>
  );
};

// 获取当前步骤
const getCurrentStep = (status) => {
  const statusMap = {
    pending: 1,
    approved: 2,
    denied: 2,
    rejected: 2,
    revoked: 2,
  };
  return statusMap[status] || 0;
};

// 获取步骤状态
const getStepStatus = (status) => {
  const statusMap = {
    approved: 'finish',
    pending: 'process',
    denied: 'error',
    rejected: 'error',
    revoked: 'error',
  };
  return statusMap[status] || 'wait';
};

// 获取结果描述
const getResultDescription = (status) => {
  const statusMap = {
    approved: '退款已通过',
    pending: '',
    denied: '退款被否决',
    rejected: '退款被驳回',
    revoked: '退款已撤销',
  };
  return statusMap[status] || '';
};

export default RefundDetails;